package WebRoot.demo5.controller;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.bson.Document;
import org.hoyi.DB.util.ConfigUtil;
import org.hoyi.dishop.Hoyipage;
import org.hoyi.nosql.mongo.HoyiMongoCluster;

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.util.JSON;

public class MongodbUtil extends Hoyipage {
	/***
	 * 插入对象到mongodb集合
	 * 
	 * @throws Exception
	 * @paramer Object 对象实体，String con 集合
	 */

	public static MongoCollection<Document> getCollection(String colName) {
		// TODO Auto-generated method stub

		MongoDatabase mongoDatabase = HoyiMongoCluster.getMongoClient()
				.getDatabase(ConfigUtil.GetMongoProperties().getProperty("mongo.db"));
		MongoCollection<Document> _collection = mongoDatabase.getCollection(colName);

		return _collection;
	}

	public static void insertMany(Document document, String collection) {
		// TODO Auto-generated method stub

		MongoDatabase mongoDatabase = HoyiMongoCluster.getMongoClient()
				.getDatabase(ConfigUtil.GetMongoProperties().getProperty("mongo.db"));
		MongoCollection<Document> _collection = mongoDatabase.getCollection(collection);
		// 增加判断 如果MongoDB没有该集合 创建集合
		List<Document> documents = new ArrayList<Document>();
		documents.add(document);
		_collection.insertMany(documents);
	}

	public static void updateOne(Document filter, Document update, String colName) {
		// TODO Auto-generated method stub

		MongoDatabase mongoDatabase = HoyiMongoCluster.getMongoClient()
				.getDatabase(ConfigUtil.GetMongoProperties().getProperty("mongo.db"));
		MongoCollection<Document> _collection = mongoDatabase.getCollection(colName);
		// 增加判断 如果MongoDB没有该集合 创建集合
		_collection.updateOne(filter, update);
	}

	public static Document ObjTransformToDoc(Object obj) {
		Class<?> clazz = obj.getClass();
		Document doc = new Document();

		for (Field field : clazz.getDeclaredFields()) {
			field.setAccessible(true);

			String fieldName = field.getName();
			Object value = null;
			try {
				value = field.get(obj);
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			value = StringUtils.trim(value != null ? value.toString() : "");
			// if (!fieldName.equals(value)) {
			// char[] cs = fieldName.toCharArray();
			// cs[0] += 32;
			// doc.append(String.valueOf(cs), value);
			// }
			doc.append(fieldName, value);

		}
		return doc;
	}

	/**
	 * MongoDB查询分页
	 */
	public static List<Map<String, String>> findPage(String colName, Document query, int page, int pageSize,
			Document sort) {
		MongoDatabase mongoDatabase = HoyiMongoCluster.getMongoClient()
				.getDatabase(ConfigUtil.GetMongoProperties().getProperty("mongo.db"));
		MongoCollection<Document> collection = mongoDatabase.getCollection(colName);

		// sort 排序 -1 倒序 1正序 limit每页条数 page 第几页
		FindIterable<Document> iterable = collection.find(query).skip((page - 1) * 10).sort(sort).limit(pageSize);
		// 查询后进行迭代

		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		MongoCursor<Document> cursor = iterable.iterator();
		while (cursor.hasNext()) {
			Document user = cursor.next();
			String jsonString = user.toJson();
			Map<String, String> jsonStrToMap = jsonStrToMap(jsonString);
			jsonStrToMap.remove("_id");
			list.add(jsonStrToMap);
		}
		return list;
	}

	/**
	 * MongoDB查询List
	 */
	public static List<Map<String, String>> findList(String colName, Document query) {
		MongoDatabase mongoDatabase = HoyiMongoCluster.getMongoClient()
				.getDatabase(ConfigUtil.GetMongoProperties().getProperty("mongo.db"));
		MongoCollection<Document> collection = mongoDatabase.getCollection(colName);

		// sort 排序 -1 倒序 1正序 limit每页条数 page 第几页
		FindIterable<Document> iterable = collection.find(query);
		// 查询后进行迭代

		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		MongoCursor<Document> cursor = iterable.iterator();
		while (cursor.hasNext()) {
			Document user = cursor.next();
			String jsonString = user.toJson();
			Map<String, String> jsonStrToMap = jsonStrToMap(jsonString);
			jsonStrToMap.remove("_id");
			list.add(jsonStrToMap);
		}

		return list;
	}

	/**
	 * 更新MongoDB(不能用)
	 */
	public static void update(String colName) {
		// 更新文档 将文档中likes=100的文档修改为likes=200
		MongoDatabase mongoDatabase = HoyiMongoCluster.getMongoClient()
				.getDatabase(ConfigUtil.GetMongoProperties().getProperty("mongo.db"));
		MongoCollection<Document> collection = mongoDatabase.getCollection(colName);
		collection.updateMany(Filters.eq("likes", 100), new Document("$set", new Document("likes", 200)));
	}

	public static Map<String, String> jsonStrToMap(String jsonString) {
		Object parseObj = JSON.parse(jsonString); // 反序列化 把json 转化为对象
		Map<String, String> map = (Map<String, String>) parseObj; // 把对象转化为map
		return map;
	}

	public static <T> T map2Bean(Map<String, String> map, Class<T> class1) {
		T bean = null;
		try {
			bean = class1.newInstance();
			BeanUtils.populate(bean, map);
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return bean;
	}

	public static <T> List<T> mapToListBean(List<Map<String, String>> listMap, Class<T> clas) {
		List<T> list = new ArrayList<>();
		try {
			if (listMap != null && listMap.size() > 0) {
				for (int i = 0; i < listMap.size(); i++) {
					T bean = clas.newInstance();
					BeanUtils.populate(bean, listMap.get(i));
					list.add(bean);
				}
			} else {
				return null;
			}
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * 删除
	 * 
	 * @param colName
	 * @param delete
	 */
	public static void delete(String colName, Document delete) {
		MongoDatabase mongoDatabase = HoyiMongoCluster.getMongoClient()
				.getDatabase(ConfigUtil.GetMongoProperties().getProperty("mongo.db"));
		MongoCollection<Document> _collection = mongoDatabase.getCollection(colName);
		_collection.deleteOne(delete);
	}

	/*
	 * public static void main(String args[]) { ServerAddress address = new
	 * ServerAddress("192.168.0.81",20020); List<ServerAddress> lists = new
	 * ArrayList<ServerAddress>(); lists.add(address); MongoCredential
	 * mongoCredential = MongoCredential.createCredential("xiaojiang", "admin",
	 * "laogeming".toCharArray()); List<MongoCredential> listm = new
	 * ArrayList<MongoCredential>(); listm.add(mongoCredential); MongoClient client
	 * = new MongoClient(lists,listm); ReadPreference preference =
	 * ReadPreference.primary(); client.setReadPreference(preference);
	 * 
	 * MongoDatabase mongoDatabase = client.getDatabase("admin");
	 * 
	 * MongoDatabase mongoDatabase = HoyiMongoCluster.getMongoClient()
	 * .getDatabase(ConfigUtil.GetMongoProperties().getProperty("mongo.db"));
	 * MongoCollection<Document> _collection = mongoDatabase.getCollection("video");
	 * BasicDBObject filter = new BasicDBObject();
	 * filter.put("videoid","10bdea88fe8e46baa80732ae9b39152d"); video v = new
	 * video(); v.setVideoid("123456"); v.setVideotitle("test01");
	 * v.setCoverpath("www.baidu.com"); BasicDBObject update = new BasicDBObject();
	 * 
	 * FindIterable<Document> iterable = _collection.find(filter); // 查询后进行迭代
	 * 
	 * List<Map<String, String>> list = new ArrayList<Map<String, String>>();
	 * MongoCursor<Document> cursor = iterable.iterator(); while (cursor.hasNext())
	 * { Document user = cursor.next(); String jsonString = user.toJson(); } }
	 */
}
